﻿using Apewer;
using Apewer.Internals;
using Apewer.Source;
using System;
using System.Collections.Generic;
using System.Text;

namespace Apewer.Network
{

    /// <summary>简单邮件传输协议客户端。</summary>
    [Serializable]
    public sealed class MailClient : Record
    {

        [NonSerialized]
        private TextSet _ts = new TextSet(false);

        [NonSerialized]
        private bool _smtpssl = false;

        [NonSerialized]
        private int _smtpport = 25;

        /// <summary>构造函数。</summary>
        public MailClient() { }

        /// <summary>构造函数。</summary>
        public MailClient(string server, string user, string pass)
        {
            Server = server;
            User = user;
            Pass = pass;
        }

        /// <summary>服务器地址。</summary>
        [Column]
        public string Server { get { return _ts["Server"]; } set { _ts["Server"] = value; } }

        /// <summary>认证用户。</summary>
        [Column]
        public string User { get { return _ts["User"]; } set { _ts["User"] = value; } }

        /// <summary>认证密码。</summary>
        [Column]
        public string Pass { get { return _ts["Pass"]; } set { _ts["Pass"] = value; } }

        /// <summary>使用安全套接字层加密连接，默认不加密。</summary>
        [Column]
        public int SmtpPort { get { return _smtpport; } set { _smtpport = value; } }

        /// <summary>使用安全套接字层加密连接，默认不加密。</summary>
        [Column]
        public bool SmtpSsl { get { return _smtpssl; } set { _smtpssl = value; } }

        /// <summary>获取 JSON 文本。</summary>
        public override string ToString()
        {
            return Json.From(this).ToString();
        }

        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="InvalidOperationException"></exception>
        internal System.Net.Mail.SmtpClient ToInstance()
        {
            var credential = new System.Net.NetworkCredential();
            credential.UserName = User;
            credential.Password = Pass;

            var instance = new System.Net.Mail.SmtpClient();
            instance.Host = Server;
            instance.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            instance.Host = Server;
            instance.Credentials = credential;

            instance.EnableSsl = SmtpSsl;
            instance.Port = SmtpPort;

            return instance;
        }

    }

}
